<template>
  <div class="page order-detail-page">
    <van-nav-bar title="订单详情" left-text="返回" left-arrow @click-left="onClickLeft" />
    <div class="container">
      <div class="cblock order-status">
        <div
          v-if="order.status == 0 || (order.status== 1 && order.win_status==0)"
          class="float-right"
        >
          <van-count-down ref="countDown" :time="countTime" :format="countFormat" />
        </div>
        <van-tag v-if="order.status == 0" type="danger">订单待支付</van-tag>
        <template v-else-if="order.status > 0">
          <van-tag v-if="order.win_status == 0" type="warning">拼团中</van-tag>
          <van-tag v-else-if="order.win_status < -1" type="danger">拼团失败</van-tag>
          <van-tag v-else-if="order.win_status < 0">未中奖</van-tag>
          <van-tag v-else-if="order.win_status > 1" type="success">拼团成功</van-tag>
          <template v-else>
            <van-tag v-if="order.status == 2" type="primary">已发货</van-tag>
            <van-tag v-else-if="order.status == 3" type="primary">已收货</van-tag>
            <van-tag v-else-if="order.status > 3" type="success">已完成</van-tag>
          </template>
        </template>
        <van-tag v-else-if="order.status == -1">已失效</van-tag>
        <van-tag v-else-if="order.status == -2">已退货/退款</van-tag>
        <van-tag v-else-if="order.status < -2" type="warning">售后中</van-tag>
      </div>

      <div class="cblock order-goods">
        <div class="goods-list">
          <div v-for="item in order.goods" :key="item.id">
            <van-card
              :num="item.count"
              :price="item.goods_price"
              :desc="item.vice_title"
              :title="item.goods_title"
              :thumb="item.goods_image"
              @click="viewGoods(item.goods_id)"
            />
          </div>
        </div>
        <van-cell title="总价" :value="order.payamount"></van-cell>
        <div class="actions">
          <template v-if="order.status == 0">
            <van-button size="small" @click="cancelOrder(order.order_id)">取消</van-button>
            <van-button size="small" type="danger" @click="payOrder(order.order_id)">支付</van-button>
          </template>
          <template v-else-if="order.status > 0">
            <template v-if="order.win_status == 0">
              <van-button
                size="small"
                type="danger"
                plain
                :to="'/group/order/'+(order.parent_order_id>0?order.parent_order_id:order.order_id)"
              >分享</van-button>
            </template>
            <template v-if="order.win_status == 1">
              <template v-if="order.status > 1">
                <van-button size="small" plain @click="expressOrder(order.order_id)">查看物流</van-button>
              </template>
              <template v-if="order.status > 2">
                <van-button
                  size="small"
                  type="info"
                  plain
                  @click="completeOrder(order.order_id)"
                >确认收货</van-button>
              </template>
            </template>
          </template>
          <template v-else>
            <van-button size="small" @click="deleteOrder(order.order_id)">删除</van-button>
          </template>
        </div>
      </div>
      <div class="cblock order-info">
        <van-cell title="订单号" :value="order.order_no">
          <van-button
            slot="right-icon"
            v-clipboard:copy="order.order_no"
            type="info"
            plain
            size="mini"
            style="margin-left:10px;"
            v-clipboard:success="onCopy"
            v-clipboard:error="onError"
          >复制</van-button>
        </van-cell>
        <van-cell title="下单时间" :value="formatDate(order.create_time)"></van-cell>
        <van-cell title="支付时间" :value="formatDate(order.pay_time)"></van-cell>
        <van-cell title="收货时间" :value="formatDate(order.confirm_time)"></van-cell>
      </div>
    </div>

    <van-action-sheet
      v-model="showPay"
      :actions="actions"
      cancel-text="取消"
      @select="onSelectPay"
      @cancel="showPay = false"
    />
    <van-popup v-model="showKeyboard" closeable position="bottom" :style="{ height: '80%' }">
      <div style="margin-top:50px;">
        <van-password-input
          v-model="secpassword"
          info="请输入安全密码"
          :focused="showKeyboard"
          @focus="showKeyboard = true"
        />
        <van-number-keyboard
          :show="showKeyboard"
          @input="onInput"
          @delete="onDelete"
          @blur="showKeyboard = false"
        />
      </div>
    </van-popup>
  </div>
</template>
<script >
import Vue from "vue";
import VueClipboard from "vue-clipboard2";
import utils from "../../utils";

Vue.use(VueClipboard);

export default {
  data() {
    return {
      order_id: 0,
      countTime: 0,
      order: {},

      showPay: false,
      actions: [{ name: "微信支付",type:'wechat' }, { name: "佣金支付",type:'reward' }],
      secpassword: "",
      showKeyboard: false
    };
  },
  computed: {
    countFormat() {
      if (this.order.status == 0) {
        return "HH:mm:ss";
      }
      return "DD 天 HH 时 mm 分 ss 秒";
    },
    config() {
      return this.$store.state.config;
    },
    member() {
      return this.$store.state.userinfo
    }
  },
  mounted() {
    let order_id = this.$route.query.id;
    if (order_id && !isNaN(order_id)) {
      this.order_id = order_id * 1;
    } else {
      this.$toast.fail("参数错误");
      this.$router.back();
    }
    this.getData();
  },
  methods: {
    onClickLeft() {
      this.$router.back();
    },
    viewGoods(goods_id) {
      this.$router.push("/group/detail/" + goods_id);
    },
    getData() {
      this.$api
        .post("member.groupbuy/view", { id: this.order_id })
        .then(json => {
          if (json.code == 1) {
            this.order = utils.fixListImage(json.data, "goods.goods_image");
            this.$nextTick().then(() => {
              this.calcTime();
            });
          }
        })
        .catch(err => {
          this.$toast.fail(err.msg || "参数错误");
          this.$router.back();
        });
    },
    calcTime() {
      if (!this.order || !this.config) return 0;
      let time = 0;
      
      if (this.order.status == 0) {
        time =
          (this.order.create_time + this.config.groupbuy_overtime * 60) * 1000 -
          new Date().getTime();
      } else if (this.order.status == 1 && this.order.win_status == 0) {
        time =
          (this.order.group_create_time +
            this.config.groupbuy_cycle * 24 * 60 * 60) *
            1000 -
          new Date().getTime();
      }
      if (time < 0) time = 0;
      this.countTime = time;
    },
    formatDate(timestamp) {
      if (!timestamp || timestamp == 0) return "-";
      return utils.dateFormat("Y-m-d H:i:s", timestamp);
    },
    cancelOrder(order_id) {
      this.$dialog
        .confirm({
          title: "取消订单",
          message: "确定取消此订单?"
        })
        .then(() => {
          this.$api
            .post("member.groupbuy/cancel", { id: order_id })
            .then(json => {
              if (json.code == 1) {
                this.$toast.success(json.msg || "操作成功");
                this.getData();
              }
            })
            .catch(err => {
              this.$toast.fail(err.msg || "操作失败");
            });
        });
    },
    deleteOrder(order_id) {
      this.$dialog
        .confirm({
          title: "删除订单",
          message: "确定删除此订单?"
        })
        .then(() => {
          this.$api
            .post("member.groupbuy/delete", { id: order_id })
            .then(json => {
              if (json.code == 1) {
                this.$toast.success(json.msg || "操作成功");
                this.$router.back();
              }
            })
            .catch(err => {
              this.$toast.fail(err.msg || "操作失败");
            });
        });
    },
    onSelectPay(item) {
      this.showPay = false;
      if (item.type == "wechat") {
        this.$api
          .wxPay(this.currentOrderId, "GB")
          .then(() => {
            this.getData();
          })
          .catch(() => {});
      } else if (item.type == "reward") {
        if(!this.member.has_secpassword){
          this.$dialog.confirm({
            message:'您还未设置安全密码\n是否现在设置'
          }).then(()=>{
            this.$router.push('/member/sec_password')
          }).catch(()=>{

          })
          return;
        }
        this.showKeyboard = true;
      }
    },
    onInput(key) {
      this.secpassword = (this.secpassword + key).slice(0, 6);
      if (this.secpassword.length >= 6) {
        this.balancePay();
      }
    },
    onDelete() {
      this.secpassword = this.secpassword.slice(0, this.secpassword.length - 1);
    },
    balancePay() {
      this.showKeyboard = false;
      this.$toast.loading()
      this.$api
        .post("order/balancepay", {
          order_id: "GB_" + this.currentOrderId,
          type: "reward",
          secpassword: this.secpassword
        })
        .then(res => {
          this.$toast.success(res.msg || "支付成功");
          this.getData();
        })
        .catch(err => {
          this.$toast.fail(err.msg || "支付失败");
        });
    },
    payOrder(order_id) {
      this.currentOrderId = order_id;
      this.showPay = true;
    },
    expressOrder(order_id) {
      console.log(order_id);
      this.$toast("功能开发中~");
    },
    completeOrder(order_id) {
      this.$dialog
        .confirm({
          title: "完成订单",
          message: "确定已收货并完成订单?"
        })
        .then(() => {
          this.$api
            .post("member.groupbuy/confirm", { id: order_id })
            .then(json => {
              if (json.code == 1) {
                this.$toast.success(json.msg || "操作成功");
                this.getData();
              }
            })
            .catch(err => {
              this.$toast.fail(err.msg || "操作失败");
            });
        });
    },
    onCopy: function() {
      this.$toast.success("复制成功");
    },
    onError: function() {
      this.$toast.fail("复制失败, 请手动选择复制");
    }
  }
};
</script>
<style lang="scss">
.order-detail-page {
  .cblock {
    margin-top: 20px;
    .goods-list {
      padding: 10px;
    }
  }
  .order-status {
    padding: 10px;
  }
  .actions {
    padding: 10px;
    text-align: right;
    .van-button {
      margin-left: 10px;
    }
  }
}
</style>